﻿import 'package:get/get.dart';
import 'exercise_state.dart';
import '../../../core/models/exercise_info.dart';
import '../../../core/repository/default_api.dart';
import 'routes.dart';

/// 锻炼控制器
class ExerciseLogic extends GetxController {
  final ExerciseState state = ExerciseState();
  final DefaultApi _api = DefaultApi();

  @override
  void onInit() {
    super.onInit();
    loadExerciseTypes();
  }

  /// 加载锻炼类型数据
  Future<void> loadExerciseTypes() async {
    state.isLoading.value = true;

    try {
      final response = await _api.queryExerciseInfoListGet<Map<String, dynamic>>(
        isShowLoading: false,
      );

      if (response != null && response['code'] == 200) {
        final List<dynamic> dataList = response['data'] ?? [];
        final exercises = dataList
            .map((json) => ExerciseInfo.fromJson(json))
            .toList();
        
        state.allExerciseTypes.value = exercises;
        state.displayedExerciseTypes.value = exercises;
      }
    } catch (e) {
      print('加载锻炼类型失败: $e');
    } finally {
      state.isLoading.value = false;
    }
  }

  /// 选择触发类型
  void selectTriggerType(String? triggerType) {
    state.selectedTriggerType.value = triggerType ?? '';
    filterExerciseTypes();
  }

  /// 设置搜索关键词
  void setSearchKeyword(String keyword) {
    state.searchKeyword.value = keyword;
    filterExerciseTypes();
  }

  /// 切换GPS筛选
  void toggleGpsFilter() {
    state.showGpsOnly.value = !state.showGpsOnly.value;
    filterExerciseTypes();
  }

  /// 筛选锻炼类型
  void filterExerciseTypes() {
    List<ExerciseInfo> filtered = state.allExerciseTypes;

    // 按触发类型筛选
    if (state.selectedTriggerType.value.isNotEmpty) {
      filtered = filtered
          .where((exercise) => exercise.triggerType == state.selectedTriggerType.value)
          .toList();
    }

    // 按GPS筛选
    if (state.showGpsOnly.value) {
      filtered = filtered.where((exercise) => exercise.hasGps).toList();
    }

    // 按关键词搜索
    if (state.searchKeyword.value.isNotEmpty) {
      filtered = filtered
          .where((exercise) =>
              exercise.exerciseName
                  .toLowerCase()
                  .contains(state.searchKeyword.value.toLowerCase()))
          .toList();
    }

    state.displayedExerciseTypes.value = filtered;
  }

  /// 选择锻炼类型
  void selectExerciseType(ExerciseInfo exerciseInfo) {
    // 如果是GPS运动，先跳转到权限提示页面
    if (exerciseInfo.hasGps) {
      Get.toNamed(ExerciseRoutes.gpsPermission, arguments: {
        'exerciseName': exerciseInfo.exerciseName,
        'exerciseInfo': exerciseInfo,
      });
    } else {
      // 非GPS运动直接开始
      _startExercise(exerciseInfo);
    }
  }

  /// 开始锻炼
  void _startExercise(ExerciseInfo exerciseInfo) {
    // 非GPS运动跳转到目标设置页面
    Get.toNamed(ExerciseRoutes.nonGpsGoalSetting, arguments: {
      'exerciseInfo': exerciseInfo,
      'defaultTab': 0, // 默认选中时间标签
    });
  }

  /// 获取触发类型列表
  List<String> getTriggerTypes() {
    final types = state.allExerciseTypes
        .map((e) => e.triggerType)
        .toSet()
        .toList();
    types.sort();
    return types;
  }

  /// 获取触发类型名称
  String getTriggerTypeName(String triggerType) {
    switch (triggerType) {
      case '1':
        return '普通';
      case '2':
        return 'GPS';
      case '3':
        return '室内/室外';
      default:
        return '其他';
    }
  }

  /// 清除筛选
  void clearFilters() {
    state.selectedTriggerType.value = '';
    state.searchKeyword.value = '';
    state.showGpsOnly.value = false;
    state.displayedExerciseTypes.value = state.allExerciseTypes;
  }
}
